package com.zhongshengnetwork.rightbe.commentstore.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.ItemTouchHelper;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.hys.utils.ImageUtils;
import com.hys.utils.InitCacheFileUtils;
import com.yalantis.ucrop.UCrop;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.commentstore.model.CommentStoreClassifyModel;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.QiniuCallBack;
import com.zhongshengnetwork.rightbe.common.QiniuUploadModel;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.QiniuModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.imageviewer.ViewData;
import com.zhongshengnetwork.rightbe.imageviewer.widget.ImageViewer;
import com.zhongshengnetwork.rightbe.lang.model.BookmarkModel;
import com.zhongshengnetwork.rightbe.lang.view.PostArticleImgAdapter;
import com.zhongshengnetwork.rightbe.login.BDThirdActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.wzt.view.GlideEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class NewCommentStoreClassifyActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    public static final String FILE_DIR_NAME = "com.zhongshengnetwork.rightbe";//应用缓存地址
    public static final String FILE_IMG_NAME = "images";//放置图片缓存
    private static final int REQUEST_PUBLISH = 1002;
    private static final int LANG_TYPE = 1119;
    private static final int REQUEST_LOCATION = 1211;//地理位置
    private static final int TAKE_PICTURE = 1212;//拍照
    private static final int CHOOSE_PICTURE = 1214;//从相册选择
    private static final int REQUEST_LABEL = 1213; //选择标签
    private static final int CROP_PICTURE = 1003;//裁剪图片
    private static final int REQUEST_PERMISSION = 10003;

    private TopBarView topbar;

    private Context mContext;
    private PostArticleImgAdapter postArticleImgAdapter;
    private ItemTouchHelper itemTouchHelper;
    private EditText et_title;

    private int imgIndex = 0;
    private QiniuModel qiniuModel = null;
    private boolean isUploading = false;
    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private Handler mHandler = null;
    private static int delay = 100;
    private static int period = 1000;  //1s
    private boolean timerFlag = false;

    private boolean isRepublish = false;
    private boolean isNewBitmap = false;

    private ImageView wzt_cover;
    private Bitmap coverBitmap = null;

    //图片浏览
    public ImageViewer imagePreivew;
    private int imgW = 0;
    List<ViewData> mViewDatas = new ArrayList<ViewData>();
    List<Object> mImageList = new ArrayList<Object>();

    private List<String> nameList = null;
    private List<String> itemList = null;
    private boolean isPublishing = false;//发布状态，控制重复发布
    private CommentStoreClassifyModel classifyModel;

    private KyLoadingBuilder loadingBuilder;

    //绑定手机号
    private boolean bindMobile(){
        if (CommonUtils.isLogin() == true){
            if (!CommonUtils.isEmpty(CustomApplication.loginModel.getNeed()) && CustomApplication.loginModel.getNeed().equals("1")){
                if (CommonUtils.isEmpty(CustomApplication.loginModel.getMobile())){
                    Intent intent = new Intent(NewCommentStoreClassifyActivity.this, BDThirdActivity.class);
                    startActivity(intent);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_comment_store_classify);

        classifyModel =  (CommentStoreClassifyModel) getIntent().getSerializableExtra("model");
        if (classifyModel == null){
            isRepublish = false;
            classifyModel = new CommentStoreClassifyModel();
            classifyModel.setClassifyId(0);
            classifyModel.setClassifyName("");
            classifyModel.setIcon("");
            classifyModel.setUserid("");
        }else {
            isRepublish = true;
        }
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        if (isRepublish == true){
            topbar.getTitleView().setText("编辑评论库");
        }
        topbar.getRightTextView().setText("发布");
        topbar.getRightTextView().setTextSize(15);
        topbar.getRightTextView().setClickable(true);
        topbar.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintKeyBoard();
                if (CommonUtils.isLogin() == false){
                    Intent intent = new Intent(NewCommentStoreClassifyActivity.this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                publishLang();
            }
        });


        imagePreivew = (ImageViewer) findViewById(R.id.imagePreivew);
        initView();

        RelativeLayout new_classify_layout = (RelativeLayout) findViewById(R.id.new_classify_layout);
        new_classify_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
        TextView t = (TextView) findViewById(R.id.et_title);
        t.setTextColor(AppThemeUtils.getInstance().getLightTextColor());
        LinearLayout et_title_line = (LinearLayout) findViewById(R.id.et_title_line);
        et_title_line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        LinearLayout et_title_line_1 = (LinearLayout) findViewById(R.id.et_title_line_1);
        et_title_line_1.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        et_title.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        et_title.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        initData();

        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (msg == null){
                    return;
                }
                switch (msg.what) {
                    case 1:
                        if (isUploading == true){
                            break;
                        }
                        isUploading = true;
                        System.out.print("开始定时\n");
                        if (coverBitmap != null && isNewBitmap == true){
                            System.out.print("开始传图\n");
                            Glide.with(NewCommentStoreClassifyActivity.this).load(classifyModel.getIcon()).placeholder(R.mipmap.bg_add_imgshow).dontAnimate().into(wzt_cover);
                            uploadImg(coverBitmap);
                        }else {
                            System.out.print("开始发布\n");
                            stopTimer();
                            uploadLang();
                            //isUploading = false;
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        back();
    }

    @Override
    public void onBackPressed()
    {
        Log.e("TAG","按下返回键了");
        back();
    }

    private void back(){
        hintKeyBoard();
        final CustomDialog.Builder builder = new CustomDialog.Builder(NewCommentStoreClassifyActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("是否要放弃本次发布？");
        builder.setPositiveButton("放弃", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteTempFile();
                finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        CustomDialog dialog = builder.create();
        dialog.show();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void initData() {

        if (isRepublish == true){
            et_title.setText(classifyModel.getClassifyName());
        }
        mContext = getApplicationContext();
        if (PermissionUtils.hasSDCard() == true){
            InitCacheFileUtils.initImgDir(FILE_DIR_NAME, FILE_IMG_NAME);//清除图片缓存
        }

    }

    private void initView() {
        wzt_cover = (ImageView) findViewById(R.id.wzt_cover);
        if (isRepublish == true){
            Glide.with(NewCommentStoreClassifyActivity.this).load(classifyModel.getIcon()).placeholder(R.mipmap.bg_add_imgshow).dontAnimate().into(wzt_cover);
        }
        wzt_cover.setClickable(true);
        wzt_cover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPublishing == true){
                    ToastUtil.show(NewCommentStoreClassifyActivity.this, "正在发布...");
                    return;
                }
                List<String> itemList = new ArrayList<String>();
                itemList.add("拍一张");
                itemList.add("从相册选择");
                ActionSheetDialog actionSheetDialog = new ActionSheetDialog(NewCommentStoreClassifyActivity.this)
                        .builder()
                        .setTitle("请选择")
                        .setCancelable(false)
                        .setCanceledOnTouchOutside(true);
                for (String s : itemList){
                    actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                        @Override
                        public void onClick(int which) {
                            if (which > 0){
                                if (which == 1){
                                    doTakePhoto();
                                }else if (which == 2){
                                    doPickPhotoFromGallery();
                                }
                            }
                        }
                    });
                }
                actionSheetDialog.show();

            }
        });
        et_title = (EditText) findViewById(R.id.bookmark_title);
    }

    /**拍照获取相片**/
    private void doTakePhoto() {
        PermissionUtils.showCamaraNote(NewCommentStoreClassifyActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    if (PermissionUtils.cameraIsCanUse() == true){
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机
                        Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),"image.jpg"));//Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"image.jpg"));
                        //指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        //直接使用，没有缩小
                        startActivityForResult(intent, TAKE_PICTURE);  //用户点击了从相机获取
                    }else {
                        ActivityCompat.requestPermissions(NewCommentStoreClassifyActivity.this,
                                new String[]{Manifest.permission.CAMERA},
                                1);
                    }

                }
            }
        });

    }

    /**从相册获取图片**/
    private void doPickPhotoFromGallery() {
        PermissionUtils.isPictureNote(NewCommentStoreClassifyActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                        && ContextCompat.checkSelfPermission(NewCommentStoreClassifyActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(NewCommentStoreClassifyActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            REQUEST_PERMISSION);
                    //ToastUtil.show(NewCommentStoreClassifyActivity.this,"亲，请开启应用对SD卡的读写权限");
                    return;
                }

                EasyPhotos.createAlbum(NewCommentStoreClassifyActivity.this, false, GlideEngine.getInstance())
                        .start(CHOOSE_PICTURE);
            }
        });

    }

    public static Uri getUriFromFile(Context context, File file) {
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(context,
                    "com.zhongshengnetwork.rightbe.fileprovider", file);//通过FileProvider创建一个content类型的Uri
        } else {
            imageUri = Uri.fromFile(file);
        }
        return imageUri;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
//                    && ContextCompat.checkSelfPermission(NewCommentStoreClassifyActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(NewCommentStoreClassifyActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                        REQUEST_PERMISSION);
//                ToastUtil.show(NewCommentStoreClassifyActivity.this,"亲，请开启应用对SD卡的读写权限");
//                return;
//            }
            // 权限被用户同意，可以做你要做的事情了。
            List<String> itemList = new ArrayList<String>();
            itemList.add("拍一张");
            itemList.add("从相册选择");
            ActionSheetDialog actionSheetDialog = new ActionSheetDialog(NewCommentStoreClassifyActivity.this)
                    .builder()
                    .setTitle("请选择")
                    .setCancelable(false)
                    .setCanceledOnTouchOutside(true);
            for (String s : itemList){
                actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        if (which > 0){
                            if (which == 1){
                                doTakePhoto();
                            }else if (which == 2){
                                doPickPhotoFromGallery();
                            }
                        }
                    }
                });
            }
            actionSheetDialog.show();
        } else {
            // 权限被用户拒绝了，可以提示用户,关闭界面等等。
            CustomDialog dialog = null;
            final CustomDialog.Builder builder = new CustomDialog.Builder(NewCommentStoreClassifyActivity.this);
            builder.setTitle("温馨提示");
            builder.setMessage("应用需要开启相机权限，是否去设置？");
            builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    //跳转App设置权限的界面
                    Intent i = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
                    String pkg = "com.android.settings";
                    String cls = "com.android.settings.applications.InstalledAppDetails";
                    i.setComponent(new ComponentName(pkg, cls));
                    i.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(i);
                    finish();
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialog = builder.create();
            dialog.show();

        }
    }

    //------------------图片相关-----------------------------

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri imageUri = null;
        if (requestCode == CHOOSE_PICTURE && resultCode == RESULT_OK) {//从相册选择完图片
            if (data != null){

                ArrayList<Photo> resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
                if (resultPhotos != null && resultPhotos.size() > 0){
                    Photo photo = resultPhotos.get(0);
                    try{

                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                            //5.0以下不裁剪
                            Bitmap bitmap = ImageUtils.getBitmap(photo.path);
                            if (bitmap != null){
                                coverBitmap = bitmap;
                                wzt_cover.setImageBitmap(bitmap);
                                isNewBitmap = true;
                            }
                        }else {
                            imageUri = getUriFromFile(CustomApplication.mContext,new File(photo.path));
                            if (imageUri == null){
                                return;
                            }
                            cropImage(imageUri);
                        }

                    }catch (Exception e){
                        ToastUtil.show(NewCommentStoreClassifyActivity.this, "亲，你选择的图片不可用，请选取其他图片试试哦");
                        NewCommentStoreClassifyActivity.uploadError("收藏夹选择封面报错："+e.getLocalizedMessage());
                    }

                }

            }
        }else if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK){

            try {

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                    //5.0以下不裁剪
                    Bitmap bitmap = ImageUtils.getBitmap(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),"image.jpg"));
                    if (bitmap != null){
                        coverBitmap = bitmap;
                        wzt_cover.setImageBitmap(bitmap);
                        isNewBitmap = true;
                    }
                }else {
                    imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),"image.jpg"));
                    if (imageUri == null){
                        return;
                    }
                    cropImage(imageUri);
                }

            }catch (Exception e){
                ToastUtil.show(NewCommentStoreClassifyActivity.this,"亲，你这次没拍好哦，再来一次哟~");
                NewCommentStoreClassifyActivity.uploadError("收藏夹拍照封面报错："+e.getLocalizedMessage());
            }

        }else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK){
            if (data == null){
                return;
            }
            try {
                final Uri resultUri = UCrop.getOutput(data);
                Bitmap bmap = BitmapFactory.decodeFile(resultUri.getEncodedPath());
                if (bmap != null){
                    coverBitmap = bmap;
                    wzt_cover.setImageBitmap(bmap);
                    isNewBitmap = true;
                }
            }catch (Exception e){
                ToastUtil.show(NewCommentStoreClassifyActivity.this, "亲，你选择的图片不可用，请选取其他图片试试哦");
                NewCommentStoreClassifyActivity.uploadError("收藏夹裁剪封面报错："+e.getLocalizedMessage());
            }

        }
    }

    //裁剪
    private void cropImage(Uri uri){

        float density = ScreenUtils.getScreenDensity(NewCommentStoreClassifyActivity.this);
        UCrop.of(uri, Uri.fromFile(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),System.currentTimeMillis() + "imageout.jpg")))//"imageout.jpg"
                .withAspectRatio(1, 1)
                .withMaxResultSize((int)(1080*density), (int)(1080*density))
                .start(NewCommentStoreClassifyActivity.this);

    }

    //以下是发布流程
    private void publishLang(){

        if (bindMobile() == true){
            return;
        }

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
//                && ContextCompat.checkSelfPermission(NewCommentStoreClassifyActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(NewCommentStoreClassifyActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                    REQUEST_PERMISSION);
//            ToastUtil.show(NewCommentStoreClassifyActivity.this,"亲，请开启应用对SD卡的读写权限");
//            return;
//        }

        if (isPublishing == true){
            ToastUtil.show(NewCommentStoreClassifyActivity.this, "发布中，请稍后...");
            return;
        }

        if (et_title.getText().length() == 0){
            classifyModel.setClassifyName("");
        }else {
            classifyModel.setClassifyName(et_title.getText().toString());
        }

        if (CommonUtils.isEmpty(classifyModel.getClassifyName())){
            ToastUtil.show(NewCommentStoreClassifyActivity.this, "亲，请输入评论库标题哦~");
            return;
        }

        if (CommonUtils.isEmpty(classifyModel.getIcon()) && coverBitmap == null){
            ToastUtil.show(NewCommentStoreClassifyActivity.this, "亲，请设置评论库封面哦~");
            return;
        }

        classifyModel.setClassifyName(classifyModel.getClassifyName().replaceAll("%","﹪"));

        isPublishing = true;
        loadingBuilder = new KyLoadingBuilder(NewCommentStoreClassifyActivity.this);
        loadingBuilder.setIcon(R.drawable.loading04);
        loadingBuilder.setText("发布中...");
        loadingBuilder.setOutsideTouchable(false);//点击空白区域是否关闭
        loadingBuilder.setBackTouchable(true);//按返回键是否关闭
        loadingBuilder.show();
        if (isNewBitmap == true){
            getUploadInfo();
        }else {
            uploadLang();
        }
    }

    //上传内容
    private void uploadLang(){
        stopTimer();
        final HashMap<String, String> map = new HashMap<String, String>();
        String url = "comment/store/create.do";
        if (isRepublish == true){
            url = "comment/store/edit.do";
            map.put("classifyId", classifyModel.getClassifyId()+"");
        }
        map.put("token", CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        map.put("icon",classifyModel.getIcon());
        map.put("title",classifyModel.getClassifyName());
        Log.e("TAG","发布参数："+map.toString());
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(final String data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            deleteTempFile();
                            loadingBuilder.dismiss();
                            ToastUtil.show(NewCommentStoreClassifyActivity.this, "发布成功");
                            setResult(RESULT_OK);
                            finish();
                        }else {
                            loadingBuilder.dismiss();
                            isPublishing = false;
                            CustomApplication.showTip(commonModel, NewCommentStoreClassifyActivity.this);
                        }
                    }
                });
            }

            @Override
            public void onError(String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingBuilder.dismiss();
                        isPublishing = false;
                        ToastUtil.show(NewCommentStoreClassifyActivity.this,"发布失败，请稍后重试");
                    }
                });
            }
        });

    }

    //删除临时文件
    private void deleteTempFile(){

    }

    //获取上传图片凭证
    private void getUploadInfo(){
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        HttpsUtils.getQiniuTokenDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                final CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    qiniuModel = GsonTools.getQiniuModel(data);
                    if (qiniuModel != null){
                        imgIndex = 0;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //接着开定时器上传图片
                                startTimer();
                            }
                        });

                    }
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loadingBuilder.dismiss();
                            isPublishing = false;
                            CustomApplication.showTip(commonModel,NewCommentStoreClassifyActivity.this);
                        }
                    });

                }
            }

            @Override
            public void onError(String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingBuilder.dismiss();
                        isPublishing = false;
                        ToastUtil.show(NewCommentStoreClassifyActivity.this,"发布失败");
                    }
                });
            }
        });
    }

    //上传图片
    private void uploadImg(Bitmap bitmap){
        new Thread(new Runnable() {
            @Override
            public void run() {
                final String name = System.currentTimeMillis()+CustomApplication.loginModel.getUid()+".jpg";
                CommonUtils.uploadBytesToQiniu(qiniuModel.getUploadtoken(), qiniuModel.getUploadurl(), name, CommonUtils.bitmapToBytes(bitmap), new QiniuCallBack() {
                    @Override
                    public void onSuccess(final String data) {
                        if (CommonUtils.isEmpty(data)){
                            uploadError("发布失败，把图片删除再试试~");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    stopTimer();
                                    loadingBuilder.dismiss();
                                    isPublishing = false;
                                    isUploading = false;
                                    ToastUtil.show(NewCommentStoreClassifyActivity.this,"发布失败，请稍后重新发布~");
                                }
                            });

                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                                        classifyModel.setIcon(data+"-square");
                                    }else {
                                        classifyModel.setIcon(data);
                                    }
                                    if (NewCommentStoreClassifyActivity.this != null){
                                        Glide.with(NewCommentStoreClassifyActivity.this).load(classifyModel.getIcon()).placeholder(R.mipmap.bg_add_imgshow).dontAnimate().into(wzt_cover);
                                    }
                                    isUploading = false;
                                    isNewBitmap = false;
                                }
                            });
                        }
                    }

                    @Override
                    public void onModelSuccess(QiniuUploadModel data) {

                    }

                    @Override
                    public void onError(String msg) {
                        uploadError("上传图片错误信息："+CommonUtils.formatString(msg));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                stopTimer();
                                loadingBuilder.dismiss();
                                isPublishing = false;
                                isUploading = false;
                                ToastUtil.show(NewCommentStoreClassifyActivity.this,"发布失败，请稍后再试试~");
                            }
                        });
                    }
                });
            }
        }){

        }.start();
    }

    private void startTimer(){
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    sendMessage(1);
                }
            };
        }
        if(mTimer != null && mTimerTask != null ){
            mTimer.schedule(mTimerTask, delay, period);
            timerFlag = true;
        }

    }

    private void stopTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
            timerFlag = false;
        }
    }

    public void sendMessage(int id){
        if (mHandler != null) {
            Message message = Message.obtain(mHandler, id);
            mHandler.sendMessage(message);
        }
    }

    //上传错误
    public static void uploadError(String msg){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("msg", msg);
        if (CustomApplication.loginModel != null) {
            map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        }
        String url = "miniapp/langappid/geterror.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                Log.e("上传错误",data+"\n");
            }

            @Override
            public void onError(String msg) {
                Log.e("上传错误信息",msg+"\n");
            }
        });

    }

}
